/*
* Copyright (c) 2025 Huawei Device Co., Ltd.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including but not limited to the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to provide persons with access to the Software
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGE OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/

import React, { useRef, useEffect, useState } from 'react';
import { useStore } from '../../store/store';
import { MessageItem, MessageList } from '../../types/types';
import { useNavigate } from 'react-router-dom';
import { BreakpointManager } from '@hadss/web_adaptive_layout_ui';
import './DetailContainer.css';
import { AvoidArea, AvoidAreaInfo, AvoidAreaType } from '../../common/windowCommon';

const DetailContainer: React.FC = () => {
  const container = useRef<HTMLDivElement>(null);
  const navigate = useNavigate();
  const [currentBp, setCurrentBp] = useState<string>('');
  const { state } = useStore();
  const [topAvoidArea, setTopAvoidArea] = useState(0);
  const [bottomAvoidArea, setBottomAvoidArea] = useState(0);
  const [messageData] = React.useState<MessageList[]>([
    {
      id: '1',
      type: 'left',
      content: '',
      isSpecial: true,
    },
    {
      id: '2',
      type: 'left',
      content: '请你喝奶茶，快点单吧！速度速度，就差你了',
    },
    {
      id: '3',
      type: 'time',
      content: '10:28',
    },
    {
      id: '4',
      type: 'right',
      content: '哈哈，今天有什么喜事',
    },
  ]);
  const [activeItem, setActiveItem] = React.useState<MessageItem>({
    id: '1',
    name: '张晓萌',
    message: '好的，我明天过来',
    time: '13:55',
    avatar: require('../../assets/images/touxiang.svg').default,
    unread: null,
  });
  const isXSOrSM = ['xs', 'sm'].includes(currentBp);

  const goHome = (): void => {
    navigate(-1);
  };

  const handleAvoidAreaChange = (event: any): void => {
    const data = event.detail as AvoidAreaInfo;
    const areaType = data.type;
    if (areaType === AvoidAreaType.TYPE_SYSTEM) {
      const topAvoidArea = (window as any).webClass?.pxToVp(data.area.topRect.height);
      setTopAvoidArea(topAvoidArea);
    }
    if (areaType === AvoidAreaType.TYPE_NAVIGATION_INDICATOR) {
      const bottomAvoidArea = (window as any).webClass?.pxToVp(data.area.bottomRect.height);
      setBottomAvoidArea(bottomAvoidArea);
    }
  };

  const setAvoidValue = (): void => {
    if ((window as any).webClass) {
      const webClass = (window as any).webClass;
      const topArea = webClass.getAvoidArea(AvoidAreaType.TYPE_SYSTEM) as AvoidArea;
      const bottomArea = webClass.getAvoidArea(AvoidAreaType.TYPE_NAVIGATION_INDICATOR) as AvoidArea;
      const topAvoidArea = webClass.pxToVp(topArea.topRect.height);
      const bottomAvoidArea = webClass.pxToVp(bottomArea.bottomRect.height);
      setTopAvoidArea(topAvoidArea);
      setBottomAvoidArea(bottomAvoidArea);
    }
  };

  useEffect(() => {
    setActiveItem(state.activeItem);
  }, [state.activeItem]);

  useEffect(() => {
    const breakpointManager = new BreakpointManager();
    const unsubscribe = breakpointManager.subscribeToBreakpoint((vp: string) => {
      setCurrentBp(vp);
    });
    setAvoidValue();
    window.addEventListener('avoidAreaChange', handleAvoidAreaChange);
    
    return (): void => {
      if (unsubscribe) {
        unsubscribe();
      }
      window.removeEventListener('avoidAreaChange', handleAvoidAreaChange);
    };
  }, []);

  return (
    <div className='detail-container'>
      <div className='container'>
        {/* 顶部导航 */}
        <div className='title-wrap' style={{ marginTop: `${topAvoidArea}px` }}>
          {
            isXSOrSM ? (
              <div className='go-back' onClick={goHome}>
                <img className='title-img' src={require('../../assets/images/left.png')} />
              </div>
            ) : ''}
          <div className='icon-wrap'>
            <div className='title'>{activeItem.name}</div>
          </div>
          <div className='icon-wrap'>
            <img src={require('../../assets/images/right.png')} />
          </div>
        </div>
        <div className='content'>
          {messageData.map((item) => (
            <div key={item.id} className='message-item'>
              {item.type === 'time' && (
                <div className='time'>{item.content}</div>
              )}
              {item.type === 'left' && (
                <div className='left-item'>
                  <img className='avatar' src={require('../../assets/images/touxiang.svg').default} />
                  {item.isSpecial ? (
                    <div className='left-item-content'>
                      <img src={require('../../assets/images/naicha.png')} />
                      <div className='tip'>芬芬邀请你喝奶茶啦！</div>
                      <img src={require('../../assets/images/naichaBJ.png')} className='naicha-bg' />
                      <div className='applet'>小程序</div>
                    </div>
                  ) : (
                    <div className='left-item-content normal'>
                      {item.content}
                    </div>
                  )}
                </div>
              )}
              {item.type === 'right' && (
                <div className='right-item'>
                  <div className='right-item-content'>{item.content}</div>
                  <img className='avatar' src={require('../../assets/images/touxiang.svg').default} />
                </div>
              )}
            </div>
          ))}
        </div>

        {/* 底部输入框 */}
        <div className='bottom-wrap' ref={container} style={{ marginBottom: `${bottomAvoidArea}px` }}>
          <div className='bottom-btn'>
            <img src={require('../../assets/images/smail.png')} className='bottom-img' />
          </div>
          <input className='input' disabled type='text' />
          <div className='bottom-btn'>
            <img src={require('../../assets/images/lt_add.png')} className='bottom-img' />
          </div>
        </div>
      </div>
    </div>
  );
};

export default DetailContainer;